package de.playmee.tasks;

import java.util.List;

import de.playmee.Channel;
import de.playmee.Playlist;
import de.playmee.Track;
import de.playmee.Weather;
import de.playmee.handler.AccountHandler;
import de.playmee.handler.PlaylistHandler;

import android.os.AsyncTask;
import android.util.Log;

public class ComputePlaylistTask extends AsyncTask<Void, Void, Void> {

private final String TAG = "PlaylistComputedListener";
	
	private PlaylistComputedListener computedListener;
	private AccountHandler aHandler;
	private PlaylistHandler pHandler;
	private Channel channel;
	private boolean hasNetworkConnection;
	private Playlist playlist;
	private Weather weather;
	
	public ComputePlaylistTask(AccountHandler aHandler, PlaylistHandler pHandler,
			Channel channel, boolean hasNetworkConnection, Weather weather,
			PlaylistComputedListener computedListener) {
		this.aHandler = aHandler;
		this.pHandler = pHandler;
		this.channel = channel;
		this.hasNetworkConnection = hasNetworkConnection;
		this.weather = weather;
		this.computedListener = computedListener;
	}

	@Override
	protected Void doInBackground(Void... params) {
		Log.i(TAG, "Initializing playlist...");
		long channelId = channel.getId();
		
		// application is connected to the internet
		if (hasNetworkConnection) {			
			// prefilter all track on the device
			List<Track> tracks = pHandler.prefilter(channel, null, weather);
			
			// compute playlist
			String link = "http://aj-nk.de/mrs/v2/main.php?method=get&user=" + aHandler.getUsername()
					+ "&ids=";
			for (Track t : tracks) {
				link += t.getIdDatabase() + ";";
			}
			link = link.substring(0, link.length()-1);
			Log.i(TAG, "Trying to compute the playlist...");
			try {
				playlist = pHandler.computePlaylist(channel, link, weather);
				Log.i(TAG, "Playlist successfully computed...");
			} catch (Exception e) {
				Log.i(TAG, "Playlist computation failed...");
				e.printStackTrace();
				playlist = new Playlist(channelId, false);
			}
					
			// store playlist in its channel
			channel.setPlaylist(playlist);
			
			// insert new playlist into database
			// or update it if there is already a playlist stored for the channel
			if (pHandler.playlistExists(channelId)) {
				pHandler.updatePlaylist(playlist);
			} else {
				pHandler.insertPlaylist(playlist);
			}
		}
		
		// application is not connected to the internet
		else {
			// load stored playlist
			playlist = pHandler.loadPlaylist(channelId);
		}
		
		return null;
	}
	
	@Override
	protected void onPostExecute(Void result) {
		// returns computed playlist to the main thread
		// or null if nothing can be played
		computedListener.onPlaylistComputed(playlist);
	}
	
	public interface PlaylistComputedListener {
		public void onPlaylistComputed(Playlist pl);
	}
}
